package com.huiyujiaoyu.powertime.ui.my;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huiyujiaoyu.base.BaseActivity;
import com.huiyujiaoyu.http.HttpApi;
import com.huiyujiaoyu.http.HttpMethods;
import com.huiyujiaoyu.powertime.R;
import com.huiyujiaoyu.powertime.model.SimpleBean;
import com.huiyujiaoyu.powertime.model.UserInfoBean;
import com.huiyujiaoyu.util.ActivityUtil;
import com.huiyujiaoyu.util.Constant;
import com.huiyujiaoyu.util.DisplayUtil;
import com.huiyujiaoyu.util.GlideUtil;
import com.huiyujiaoyu.util.PicCameraLocalUtil;
import com.huiyujiaoyu.util.PopupWindowUtil;
import com.huiyujiaoyu.util.StringUtils;
import com.huiyujiaoyu.util.ToastUtil;
import com.huiyujiaoyu.widget.LlkjToolBar;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

import static com.huiyujiaoyu.util.Constant.RX_CA_WRI;
import static com.huiyujiaoyu.util.Constant.addPhoto;
import static com.huiyujiaoyu.util.PicCameraLocalUtil.revitionImageSize;
import static com.huiyujiaoyu.util.StringUtils.getSubStringEnd;

/**
 * Created by win7 on 2017/6/18.
 * 我的收藏
 */

public class FeedBackActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{
    @BindView(R.id.toolbar)
    LlkjToolBar mToolbar;
    @BindView(R.id.et_desc)
    EditText mEtDesc;
    @BindView(R.id.tv_num)
    TextView mTvNum;
    @BindView(R.id.recycler)
    RecyclerView recycler;

    @BindView(R.id.btn_submit)
    Button mBtnSubmit;
    private PopupWindow pw;
    private int fromType = 1;
    private File cameraFile;
    private String picpath,content;

    private List<String> pic;
    private BaseQuickAdapter<String,BaseViewHolder> adapter;
    public static void launch(Context context) {
        ActivityUtil.startActivity(context, FeedBackActivity.class);
    }

    @Override
    protected void initView() {
        super.initView();
        setToolbar(mToolbar);
        mToolbar.setToolBar("意见反馈", true, "", R.mipmap.icon_titlebar_back, false, "", LlkjToolBar.isNull);
        pw = PopupWindowUtil.getPopupWindowFromBottom(this, new PopupWindowUtil.PhotoDoWhat() {
            @Override
            public void doone() {
                fromType = 1;
                checkPer();
            }

            @Override
            public void dotwo() {
                fromType = 0;
                checkPer();

            }
        }, "拍照", "相册");
        pic = new ArrayList<>();
        pic.add(Constant.addPhoto);
        adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.cell_pic,pic) {
            @Override
            protected void convert(BaseViewHolder helper, final String item) {
                int width = DisplayUtil.getWidth(mContext,10,3,10);
                ImageView iv = helper.getView(R.id.iv_content);
                ImageView iv2 = helper.getView(R.id.tv_delete);
                iv.getLayoutParams().width = width;
                iv.getLayoutParams().height = width;
                if(addPhoto.equals(item)){
                    GlideUtil.loadImg(iv,R.drawable.yijianfankui_tianjia);
                    iv2.setVisibility(View.INVISIBLE);
                }else{
                    GlideUtil.loadImg(iv,item);
                    iv2.setVisibility(View.VISIBLE);
                }
                iv2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pic.remove(item);
                        if(!pic.contains(addPhoto)&&pic.size()<3){
                            pic.add(pic.size(),addPhoto);
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
                helper.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(addPhoto.equals(item)){
                            PopupWindowUtil.showBottom(FeedBackActivity.this, pw, v);
                        }
                    }
                });
            }
        };
        recycler.setLayoutManager(new GridLayoutManager(mContext,3));
        recycler.setAdapter(adapter);

    }

    @Override
    protected void initListener() {
        super.initListener();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_feedback;
    }


    @OnClick({R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
                content = mEtDesc.getText()+"";
                if(TextUtils.isEmpty(content)){
                    ToastUtil.makeShortText(mContext,"请输入内容");
                    return;
                }
                HttpMethods.getInstance().feedback(mContext,getComp(),this,content,getPics());
                break;
        }
    }

    public String getPics(){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < pic.size(); i++) {
            if(!pic.get(i).equals(addPhoto)){
                sb.append(pic.get(i)+",");
            }
        }
        return getSubStringEnd(sb.toString(),",");
    }


    private void checkPer() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
            getPic();
        } else {
            EasyPermissions.requestPermissions(this, "拍照需要摄像头权限",
                    RX_CA_WRI, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //成功
        getPic();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        ToastUtil.makeShortText(mContext, "你拒绝了相应的权限");

    }
    public void getPic() {
        if (fromType == 0) {
            PicCameraLocalUtil.selectPicFromLocal(FeedBackActivity.this);
        } else if (fromType == 1) {
            cameraFile = PicCameraLocalUtil.selectPicFromCamera(FeedBackActivity.this, cameraFile);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case Constant.REQUEST_CODE_LOCAL:// 直接从相册获取
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        String picturePath = PicCameraLocalUtil.getPicByUri(
                                this, selectedImage);
                        try {
                            picpath =  revitionImageSize(
                                    picturePath, this).getAbsolutePath();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if(!TextUtils.isEmpty(picpath)){
                            uploadImag();
                        }else{
                            ToastUtil.makeShortText(mContext,"文件为空");
                        }
                    }
                }
                PopupWindowUtil.dissPw(pw);
                break;
            case Constant.REQUEST_CODE_CAMERA:// 调用相机拍照
                if (cameraFile != null && cameraFile.exists()) {
                    //上传图片
                    try {
                        picpath =   PicCameraLocalUtil.revitionImageSize(cameraFile.getAbsolutePath(), this).getAbsolutePath();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if(!TextUtils.isEmpty(picpath)){
                        uploadImag();
                    }else{
                        ToastUtil.makeShortText(mContext,"文件为空");
                    }
                }
                PopupWindowUtil.dissPw(pw);
                break;
        }
    }
    @Override
    public void onNext(Object o, int httpcode) {
        super.onNext(o, httpcode);
        switch (httpcode) {
            case HttpApi.HTTP_UPLOADIMG:
                pic.add(pic.size()-1,((SimpleBean) o).url);
                if(pic.size()>3&&pic.contains(addPhoto)){
                    pic.remove(addPhoto);
                }
                adapter.notifyDataSetChanged();
                break;
            case HttpApi.HTTP_FEEDBACK:
                    ToastUtil.makeShortText(mContext,"反馈成功");
                    finish();
                break;
        }
    }

    public void uploadImag(){
        HttpMethods.getInstance().uploadimg(mContext,getComp(),this,2,picpath);
    }
}
